<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '检测项点',
  },
}
</route>

<script lang="ts" setup>
import type { ItemPointGetParams3 } from '@/service/app/types'
import { userCenterGet6, userCenterGet7 } from '@/service/app/userCenter'

defineOptions({
  name: 'Detection',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 分类列表
const categories = ref<any[]>([])
const selectedCategory = ref('')

// 检测项点列表
const itemPointList = ref<any[]>([])
const currentPage = ref(1)
const hasMore = ref(true)
const isLoading = ref(false)

// 防抖定时器
let debounceTimer: number | null = null

// 加载分类列表
async function loadCategories() {
  try {
    const result = await userCenterGet6({
      params: {
        'condition.page': 1,
        'condition.size': 20,
      },
    })
    const apiCategories = result?.data || []

    // 在分类列表最前面添加"全部"选项
    categories.value = [
      {
        id: 'all',
        categoryId: 'all',
        name: '全部',
        title: '全部',
        categoryName: '全部',
      },
      ...apiCategories,
    ]

    console.log('加载的分类数据:', categories.value)
    if (categories.value.length > 1) {
      console.log('第一个分类的详细信息:', categories.value[1])
    }

    if (categories.value.length > 0) {
      // 默认选中"全部"
      selectedCategory.value = 'all'
      console.log('设置默认分类:', selectedCategory.value, '类型:', typeof selectedCategory.value)
      // 手动加载第一页数据
      currentPage.value = 1
      hasMore.value = true
      loadItemPoints()
    }
  }
  catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 加载检测项点列表
async function loadItemPoints() {
  if (isLoading.value || !hasMore.value)
    return

  isLoading.value = true
  try {
    const params: ItemPointGetParams3 = {
      'condition.page': currentPage.value,
      'condition.size': 10,
      'condition.listStatus': 1, // 只显示已上架的项目
    }

    // 只有不是"全部"时才传递分类参数
    if (selectedCategory.value && selectedCategory.value !== 'all') {
      const categoryId = Number.parseInt(selectedCategory.value, 10)
      if (!Number.isNaN(categoryId) && categoryId > 0) {
        params['condition.categoryId'] = categoryId
        console.log('添加分类参数:', selectedCategory.value, '转换为:', categoryId)
      }
      else {
        console.log('分类ID转换失败或无效:', selectedCategory.value)
        return
      }
    }
    else {
      console.log('不添加分类参数，显示全部')
    }

    console.log('加载检测项点参数:', params)
    const result = await userCenterGet7({ params })
    const newItems = result?.data?.data || []

    if (currentPage.value === 1) {
      itemPointList.value = newItems
    }
    else {
      itemPointList.value.push(...newItems)
    }

    hasMore.value = newItems.length === 10
    if (hasMore.value) {
      currentPage.value++
    }
  }
  catch (error) {
    console.error('加载检测项点失败:', error)
  }
  finally {
    isLoading.value = false
  }
}

// 处理分类变化
function handleCategoryChange(categoryInfo: any) {
  console.log('=== 分类变化事件触发 ===')
  console.log('接收到的分类信息:', categoryInfo, '类型:', typeof categoryInfo)

  // 从对象中提取 name 字段
  const categoryId = categoryInfo?.name || categoryInfo
  console.log('提取的分类ID:', categoryId, '类型:', typeof categoryId)
  console.log('当前选中分类:', selectedCategory.value, '类型:', typeof selectedCategory.value)

  // 清除之前的定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }

  // 防抖处理
  debounceTimer = setTimeout(() => {
    const newCategoryId = String(categoryId)
    if (selectedCategory.value !== newCategoryId) {
      console.log('更新选中分类:', selectedCategory.value, '->', newCategoryId)
      selectedCategory.value = newCategoryId
      currentPage.value = 1
      hasMore.value = true
      itemPointList.value = [] // 清空当前列表
      console.log('准备加载检测项点，分类ID:', newCategoryId)
      loadItemPoints()
    }
    else {
      console.log('分类未变化，跳过加载')
    }
  }, 100) // 100ms 防抖
}

// 查看检测项点详情
function viewItemPoint(item: any) {
  console.log('查看检测项点详情:', item)
  uni.showToast({
    title: '详情页面开发中',
    icon: 'none',
  })
}

// 页面触底加载更多
onReachBottom(() => {
  loadItemPoints()
})

// 页面加载时初始化
onMounted(async () => {
  await loadCategories()
  // loadCategories 内部已经处理了数据加载
})
</script>

<template>
  <view
    class="min-h-screen"
    :style="{
      marginTop: `${safeAreaInsets?.top}px`,
      background: 'linear-gradient(to bottom, #E9F0FF, #F2F5F9)',
    }"
  >
    <!-- 分类选择器 -->
    <view
      class="sticky top-0 z-10 shadow-sm"
      :style="{ background: 'linear-gradient(to bottom, #E9F0FF, #F2F5F9)' }"
    >
      <wd-tabs
        :model-value="selectedCategory"
        :sticky="false"
        :scrollable="true"
        :show-line="true"
        :ellipsis="true"
        line-height="2px"
        line-color="#3b82f6"
        active-color="#3b82f6"
        inactive-color="#6b7280"
        @change="handleCategoryChange"
        @click="(e) => console.log('tabs点击事件:', e)"
      >
        <wd-tab
          v-for="category in categories"
          :key="category.id || category.categoryId"
          :name="String(category.id || category.categoryId)"
          :title="category.name || category.title || category.categoryName"
          @click="() => console.log('点击了分类:', category)"
        />
      </wd-tabs>
    </view>

    <!-- 检测项点列表 -->
    <view class="p-4">
      <view v-if="isLoading && itemPointList.length === 0" class="py-8 text-center text-gray-500">
        加载中...
      </view>

      <view v-else-if="itemPointList.length > 0" class="space-y-4">
        <view
          v-for="(item, index) in itemPointList"
          :key="item.id || index"
          class="rounded-xl bg-white p-4 shadow-sm"
          @click="viewItemPoint(item)"
        >
          <!-- 检测项点标题 -->
          <view class="mb-3 flex items-start justify-between">
            <view class="flex-1">
              <view class="mb-2 text-lg text-gray-800 font-medium">
                {{ item.itemName || '检测项点' }}
              </view>
              <view class="line-clamp-2 text-sm text-gray-500">
                {{ item.itemContent || '检测项点描述' }}
              </view>
            </view>
            <view class="ml-3 flex-shrink-0">
              <text class="i-carbon-chevron-right text-xl text-gray-400" />
            </view>
          </view>

          <!-- 检测项点信息 -->
          <view class="space-y-2">
            <!-- 分类信息 -->
            <view v-if="item.categoryName" class="flex items-center">
              <text class="i-carbon-category mr-2 text-sm text-gray-400" />
              <view class="rounded-full bg-blue-100 px-3 py-1 text-xs text-blue-600">
                {{ item.categoryName }}
              </view>
            </view>

            <!-- 热门标签 -->
            <view v-if="item.isPopular" class="flex items-center">
              <text class="i-carbon-star-filled mr-2 text-sm text-yellow-500" />
              <view class="rounded-full bg-yellow-100 px-2 py-1 text-xs text-yellow-600">
                热门检测
              </view>
            </view>

            <!-- 上架状态 -->
            <view class="flex items-center">
              <text class="i-carbon-status mr-2 text-sm text-gray-400" />
              <view
                class="rounded-full px-2 py-1 text-xs"
                :class="
                  item.listStatus === 1
                    ? 'bg-green-100 text-green-600'
                    : 'bg-gray-100 text-gray-600'
                "
              >
                {{ item.listStatus === 1 ? '已上架' : '待上架' }}
              </view>
            </view>

            <!-- 上传时间 -->
            <view class="flex items-center">
              <text class="i-carbon-time mr-2 text-sm text-gray-400" />
              <view class="text-sm text-gray-600">
                上传时间：{{ item.uploadTime }}
              </view>
            </view>

            <!-- 上传用户 -->
            <view class="flex items-center">
              <text class="i-carbon-user mr-2 text-sm text-gray-400" />
              <view class="text-sm text-gray-600">
                上传者：{{ item.uploadUser }}
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="py-12 text-center">
        <text class="i-carbon-search text-6xl text-gray-300" />
        <view class="mt-4 text-gray-500">
          暂无检测项点
        </view>
      </view>

      <!-- 加载更多状态 -->
      <view v-if="itemPointList.length > 0" class="py-4 text-center">
        <view v-if="isLoading" class="text-gray-500">
          加载中...
        </view>
        <view v-else-if="!hasMore" class="text-sm text-gray-400">
          没有更多了
        </view>
      </view>
    </view>

    <!-- 底部信息 -->
    <FgFooter />
  </view>
</template>
